package com.aidex.biz.controller;

import com.aidex.biz.domain.DocType;
import com.aidex.biz.service.DocTypeService;
import com.aidex.common.annotation.Log;
import com.aidex.common.constant.Constants;
import com.aidex.common.core.controller.BaseController;
import com.aidex.common.core.domain.AjaxResult;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.domain.TreeNode;

import com.aidex.common.enums.BusinessType;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.List;
import java.util.Map;

/**
 * 文档类型信息管理
 * @author ruoyi
 */

@RestController
@RequestMapping("/biz/docType")
public class DocTypeController extends BaseController {

    @Autowired
    private DocTypeService docTypeService;

    /**
     * 根据层级展开文件类型树表格
     * @param level 展开层级
     * @param id 起始展开ID
     * @return com.aidex.common.core.domain.R
     */
    @GetMapping("/list/{level}/{id}")
    public R list(@PathVariable("level") @NotEmpty int level, @PathVariable("id") String id) {
        if (level == 0) {
            level = 2;
        }

        DocType docType=new DocType();
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            docType.setCompanyId(null);
           // id = Constants.TREE_ROOT;
        }else{
            docType.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
           // id = SecurityUtils.getLoginUser().getUser().getDocType().getParentId();
        }
        List<DocType> depts = docTypeService.listDataByLevel(docType,level, id);
        return R.data(depts);
    }
    @GetMapping("/alllist")
    public R alllist(DocType docType) {
        List<DocType> depts = docTypeService.findList(docType);
        return R.data(depts);
    }
    /**
     * 文件类型树表格检索
     */
    @GetMapping("/searchDeptList")
    public R searchDeptList (DocType docType)
    {
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            docType.setCompanyId(null);
        }else{
            docType.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        List<DocType> depts =  docTypeService.searchDeptList(docType);
        return R.data(depts);
    }
    /**
     * 根据ID获取文件类型信息
     * @param id
     * @return com.aidex.common.core.domain.R
     */
    @GetMapping(value = "/{id}")
    public R detail(@NotBlank @PathVariable String id) {
        DocType docType = docTypeService.get(id);
        DocType parentDept = docTypeService.get(docType.getParentId());
        if(parentDept != null){
            docType.setParentName(parentDept.getDeptName());
            docType.setParentDeptType(parentDept.getDeptType());
        }
        return R.data(docType);
    }

    /**
     * 获取当前父节点下最大编号
     * @param parentId
     * @return com.aidex.common.core.domain.R
     */
    @Log(title = "岗位管理", businessType = BusinessType.SELECT)
    @GetMapping("/findMaxSort/{parentId}")
    public R findMaxSort(@PathVariable("parentId") String parentId) {

        DocType docType=new DocType();
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            docType.setCompanyId(null);
        }else{
            docType.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        
        docType.setParentId(parentId);
        return R.data(docTypeService.findMaxSort(docType));
    }

    /**
     * 校验同一个父文件类型下是否存在同名的文件类型
     * @param deptName 文件类型名称
     * @param parentId 父文件类型ID
     * @param id
     * @return com.aidex.common.core.domain.R
     */
    @PreAuthorize("@ss.hasPermi('system:post:edit')")
    @Log(title = "文件类型管理", businessType = BusinessType.CHECK)
    @GetMapping(value = {"/validateDeptNameUnique/{deptName}/{parentId}/{id}", "/validateDeptNameUnique/{deptName}/{parentId}"})
    public R validateDeptNameUnique(@NotBlank(message = "文件类型名称不允许为空") @PathVariable("deptName") String deptName, @NotBlank(message = "ID不允许为空")  @PathVariable("parentId") String parentId, @PathVariable(value = "id", required = false) String id) {

        DocType docType=new DocType();
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            docType.setCompanyId(null);
        }else{
            docType.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        docType.setParentId(parentId);
        docType.setDeptName(deptName);
        docType.setId(id);
        docTypeService.checkDeptNameUnique(docType);
        return R.status(Boolean.TRUE);
    }

    /**
     * 新增文件类型
     * @param dept
     * @return com.aidex.common.core.domain.R
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "文件类型管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody @Validated  DocType dept) {
        docTypeService.save(dept);
        return R.data(dept);
    }

    /**
     * 修改文件类型
     * @param dept
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "文件类型管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody @Validated  DocType dept) {
        docTypeService.save(dept);
        return R.data(dept);
    }

    /**
     * 删除文件类型
     * @param id
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "文件类型管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public R remove(@PathVariable  String id) {
        DocType docType = new DocType();
        docType.setId(id);
        return R.status(docTypeService.remove(docType));
    }

    /**
     * 文件类型选择树
     * @param level 初始展开层级
     * @param id 展开节点ID
     * @return
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/listTree/{level}/{id}")
    public R listTree(@NotBlank @PathVariable("level") int level, @PathVariable("id") String id) {
        if (level == 0) {
            level = 2;
        }

        DocType docType=new DocType();
//        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
//            docType.setCompanyId(null);
//            //id= Constants.TREE_ROOT;
//        }else{
//            docType.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
//           // id = SecurityUtils.getLoginUser().getUser().getDocType().getParentId();//默认根据当前登陆对下的父节点
//        }
        List<TreeNode> depts = docTypeService.buildDeptTree(docType,level, id);
        return R.data(depts);
    }
    /**
     * 文件类型树检索
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/search")
    public R search (DocType docType)
    {
        List<TreeNode> depts =  docTypeService.search(docType.getDeptName());
        return R.data(depts);
    }

    /**
     * 文件类型选择树
     * @param level
     * @param id
     * @param excludeId 排除节点
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping(value = {"/listTreeExcludeChild/{level}/{id}/{excludeId}"})
    public R listTreeExcludeChild(@NotBlank @PathVariable("level") int level, @PathVariable("id") String id, @PathVariable(value = "excludeId",required = false) String excludeId) {
        if (level == 0) {
            level = 2;
        }
        id = SecurityUtils.getLoginUser().getUser().getSysDept().getParentId();//默认根据当前登陆对下的父节点
        DocType docType=new DocType();
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            docType.setCompanyId(null);
        }else{
            docType.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        List<TreeNode> depts = docTypeService.buildDeptTreeExcludeChild(docType,10, id,excludeId);
        return R.data(depts);
    }

    /**
     * 加载对应角色文件类型列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public R roleDeptTreeselect(@PathVariable("roleId") String roleId) {
        DocType docType=new DocType();
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
            docType.setCompanyId(null);
        }else{
            docType.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        }
        List<DocType> depts = docTypeService.findList(docType);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", docTypeService.selectDeptListByRoleId(roleId));
        ajax.put("depts", docTypeService.buildDeptTreeExcludeChild(docType,-1, Constants.TREE_ROOT,null));
        return R.data(ajax);
    }

    /**
     * 选人页面按文件类型加载
     * @param level 初始展开层级
     * @param id 展开节点ID
     * @return
     */
    @GetMapping("/userSelectList/{level}/{id}")
    public R userSelectList(@NotBlank @PathVariable("level") int level, @PathVariable("id") String id) {
        if (level == 0) {
            level = 2;
        }
        //默认为根节点
        if (StringUtils.isEmpty(id)) {
            id = Constants.TREE_ROOT;
        }
        List<TreeNode> depts = docTypeService.buildDeptSelectUserTree(level, id);
        return R.data(depts);
    }
    /**
     * 按文件类型树检索用户
     */
    @GetMapping("/searchDeptUserList")
    public R searchDeptUserList (DocType docType)
    {
        List<TreeNode> depts =  docTypeService.searchDeptUserList(docType);
        return R.data(depts);
    }


    /**
     * 通用选人页面根据用户ID
     * @return
     */
    @PostMapping(value = { "/getDeptInfoByIds"})
    public R getDeptInfoByIds(@Validated @RequestBody JSONObject deptIdsObj)
    {
        List<Map<String,Object>> docTypeList = docTypeService.getDeptInfoByIds(deptIdsObj);
        return R.data(docTypeList);
    }
}
